import React, {Component} from 'react';
import {Button, Input, Tooltip, Modal, Spin} from 'antd';
import {connect} from 'react-redux';
import utils from '../../utils';

import {loadData, loadDetail, loadAddress} from './redux';

import './system.bundle.less';

class System extends Component {

    state = {
        webSrc: '',
        isOpen: null,
        color: '',
        text: '',
        spinTip: '',
        detail: 'none',
        visible: false,
        load: false,
    }
    componentDidMount() {
        if (!this.props.labload) {
            this.props.loadData();
        }
        if (!this.props.detailload) {
            this.props.loadDetail();
        }
        if (!this.props.addressload) {
            this.props.loadAddress();
        }
    }

    caseSubmit = (state) => {
        switch (state) {
            case 'RUNAGAIN':
                return (
                    Modal.warning({
                        title: 'warning',
                        content: `Please change dir into experiment's package, and run again.`
                    })
                );
            case 'SUCCESS':
                return (
                    Modal.success({
                        title: 'success',
                        content: `The experiment's package submit succeed.`
                    })
                );
            case 'SUBMITFAIL':
                return (
                    Modal.error({
                        title: 'failed',
                        content: `The experiment's package submit failed.`
                    })
                );
            case 'EXITS':
                return (
                    Modal.success({
                        title: 'success',
                        content: `The experiment's package submit succeed.`
                    })
                );
        }
    }

    handleSubmit = ()=> {
        let data = utils.get('/api/submitexperiment', null, '');
        data.then(res => {
            if (res.code === -1) {
                utils.showGlobalError('无法上传当前实验', '错误提示', true);
            } else {
                let result = res.data.split('|');
                this.caseSubmit(result[0]);
            }
        });
    }

    handleOk = (e) => {
        let data = utils.get('/api/submitexperiment', {opt: '0'}, '');
        this.setState({
            visible: false
        });
        data.then(res => {
            if (res.code === -1) {
                utils.showGlobalError('无法上传当前实验', '错误提示', true);
            } else {
                let result = res.data.split('|');
                this.caseSubmit(result[0]);
            }
        });
    }

    handleCancel = (e) => {
        let data = utils.get('/api/submitexperiment', {opt: '1'}, '');
        this.setState({
            visible: false
        });
        data.then(res => {
            if (res.code === -1) {
                utils.showGlobalError('无法上传当前实验', '错误提示', true);
            } else {
                let result = res.data.split('|');
                this.caseSubmit(result[0]);
            }
        });
    }

    componentDidUpdate() {
        if (this.props.addressload && this.state.isOpen === null) {
            if (this.props.address.code === -1) {
                utils.showGlobalError('未检测到有已打开的实验，请开始实验', '错误提示', true);
                return;
            }
            let data = this.props.address.data;
            data = data.split('|');
            if (data.indexOf('UNSTARTED') !== -1) {
                this.setState({
                    color: '#fff',
                    webSrc: '',
                    text: '开机',
                    isOpen: false
                });
                this.refs.urltool.refs.input.value = '';
            } else {
                let resultsPost = data[0].split(':')[2];
                let address = `http://132.232.171.110:${resultsPost}`;
                this.setState({
                    color: '#f00',
                    isOpen: true,
                    webSrc: address,
                    text: '关机'
                });
                this.refs.urltool.refs.input.value = address;
            }
        }
    }
    handlePowerOff = (e) => {
        if (this.state.isOpen) {
            let data = utils.get('/api/stopexperiment', null, '');
            data.then(res => {
                let result = res.data.split('|');
                if (res.code === -1 && result[0] !== 'STOPED') {
                    utils.showGlobalError('无法停止当前实验', '错误提示', true);
                } else {
                    Modal.success({
                        title: '关机成功',
                        content: '已关机'
                    });
                    this.setState({
                        isOpen: false,
                        webSrc: '',
                        load: false,
                        color: '#fff',
                        text: '开机'
                    });
                    this.refs.urltool.refs.input.value = '';
                }
            });
        } else {
            let data = utils.get('/api/startexperiment', null, '');
            data.then(res => {
                if (res.code === -1) {
                    utils.showGlobalError('无法开始当前实验', '错误提示', true);
                } else {
                    let result = res.data.split('|')[0];
                    let resultsPost = result.split(':')[2];
                    let address = `http://132.232.171.110:${resultsPost}`;
                    this.setState({
                        isOpen: true,
                        webSrc: address,
                        color: '#f00',
                        spinTip: '正在开机...',
                        load: true,
                        text: '关机'
                    });
                    this.refs.urltool.refs.input.value = address;
                }
            });
        }
    }

    loading = (e) => {
        this.setState({
            load: false
        });
    }

    handleEnter = (e) => {
        let url = this.refs.urltool.refs.input.value;
        if (this.state.isOpen) {
            this.setState({webSrc: url});
        }
    }

    handleDetail = (e) => {
        if (this.state.detail === 'none') {
            this.setState({
                detail: ''
            });
        } else {
            this.setState({
                detail: 'none'
            });
        }
    }

    render() {
        const labdata = this.props.labdata;
        const detail = this.props.detail;
        return (
            <div className="system">
                <div className='title'>
                    {`实验列表----当前实验${(!labdata.code === -1 && this.props.labload) ? utils.showGlobalError('无法打开当前实验', '错误提示', true) : labdata.labname}`}
                    <hr />
                </div>
                <div className='insert'>
                    <div className='toolbar'>
                        <Tooltip placement="bottom" title={this.state.text}>
                            <Button ref='poweroff' className='poweroff' shape="circle" icon="poweroff"
                                onClick={this.handlePowerOff}
                                style={{color: this.state.color}}/>
                        </Tooltip>
                        <Button className='upload' icon='upload' onClick={this.handleSubmit}>上传实验结果</Button>
                        <Input
                            ref='urltool'
                            className='urltool'
                            placeholder="Please enter your URL before starting up"
                            addonAfter={
                                <Tooltip placement="bottom" title='转到'>
                                    <Button className='enter' icon="enter" disabled={!this.state.isOpen} onClick={this.handleEnter}/>
                                </Tooltip>
                            }
                        />
                        <Tooltip placement="bottom" title='实验详情'>
                            <Button className='ctrldetail poweroff' icon='file-text' shape='circle' onClick={this.handleDetail}/>
                        </Tooltip>
                    </div>
                    <div
                        className='detail'
                        ref='detail'
                        style={{display: this.state.detail}}
                        dangerouslySetInnerHTML={{__html: detail.data}}
                    >
                    </div>
                    <Spin tip={this.state.spinTip} spinning={this.state.load} delay={500}>
                        <iframe frameBorder='no'
                            allowtransparency={'' + !this.state.isOpen}
                            src={this.state.webSrc}
                            style={{background: 'rgba(121, 118, 118)'}}
                            onLoad={this.loading}></iframe>
                    </Spin>
                </div>
                <Modal
                    title="上传实验结果"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <p>{`You have been submitted experiment package of ${labdata.labname}.do you want to replace it?`}</p>
                </Modal>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return state.system;
}

function mapDispatchToProps(dispatch) {
    return {
        loadData() {
            return dispatch(loadData());
        },
        loadDetail() {
            return dispatch(loadDetail());
        },
        loadAddress() {
            return dispatch(loadAddress());
        }
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(System);
